package com.xtayfjpk.zookeeper.test.master_workers.callback.master;

import org.apache.log4j.Logger;
import org.apache.zookeeper.data.Stat;

import com.xtayfjpk.zookeeper.test.master_workers.Master;
import com.xtayfjpk.zookeeper.test.master_workers.Master.MasterStates;
import com.xtayfjpk.zookeeper.test.master_workers.callback.BaseStatCallback;

public class MasterExistsCallback extends BaseStatCallback {
	private static final Logger LOGGER = Logger.getLogger(MasterExistsCallback.class);
	private Master master;
	
	public MasterExistsCallback(Master master) {
		this.master = master;
	}
	
	@Override
	protected void connectionLossCaseAction(int rc, String path, Object ctx,
			Stat stat) {
		master.exists();
	}
	
	@Override
	protected void noNodeCaseAction(int rc, String path, Object ctx, Stat stat) {
		master.setState(MasterStates.RUNNING);
		/**
		 * 如果/master节点不存在，则竞争成为master
		 */
		master.runForMaster();
		LOGGER.info("It sounds like the previous master is gone, " +
         		"so let's run for master again.");
	}
	
	@Override
	protected void defaultCaseAction(int rc, String path, Object ctx, Stat stat) {
		master.checkMaster();
	}
}
